package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {


    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;


    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password) {
        try {
            // 从 Shiro 安全工具中获取主体对象(也就是要登录的事务, 人, 程序, 机器....)
            Subject subject = SecurityUtils.getSubject();
            // 根据前端传来的用户名和密码, 组成口令凭证对象
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            // 让登录主体携带口令, 执行登录操作, 进行认证
            subject.login(token);
            // 登录成功, 返回JSON信息
            return new JsonResult(true,username+",欢迎您!");
        }catch (UnknownAccountException e){
            // Shiro 认证过程中, 抛出此异常, 说明该用户不存在
            e.printStackTrace();
            return new JsonResult(false,"用户不存在!");
        }catch (IncorrectCredentialsException e){
            // Shiro 认证过程中, 抛出此异常, 说明该用户存在, 但是密码不正确
            e.printStackTrace();
            return new JsonResult(false,"密码不正确!");
        }catch (Exception e){
            // 其他异常
            e.printStackTrace();
            return new JsonResult(false,"登录系统异常,请联系管理员!");
        }

    }
}
